import { Component, ErrorInfo, Fragment, ReactNode } from "react";

class ErrorBoundary extends Component<{ children: ReactNode }> {
  state = {
    isError: false
  }

  static getDerivedStateFromError(error: Error) {
    console.log(error)
    if (error) {
      return { isError: true }
    }
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
    console.log(error, errorInfo)
  }

  render(): ReactNode {
    const Error = (
      <div className="w-full h-full flex-center">
        <span>--这是错误组件--</span>
      </div>
    )

    return (
      <Fragment>
        {!this.state.isError && this.props.children}
        {this.state.isError && Error}
      </Fragment>
    )
  }
}

export default ErrorBoundary